package com.user.query.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import sun.misc.BASE64Decoder;

import com.user.query.model.User;
import com.user.query.utils.HttpCode;

/**
 * 文件上传工具类
 * 
 * @author chuzz
 * 
 */
@Controller
public class FileUploadController extends BaseController{

	private SimpleDateFormat ym_format = new SimpleDateFormat("yyyyMM");
	private SimpleDateFormat ymd_format = new SimpleDateFormat("yyyy/MM/dd");
	@RequestMapping("/image/upload")
	@ResponseBody
	public Map<String, Object> upload(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		String fileName = UUID.randomUUID().toString();
		try {
			response.setContentType("text/html;charset=utf-8");
			String filePath = "";
			// String sss = request.getParameter("filename");
			Date now = new Date();  
			/*String pathDir = request.getSession().getServletContext()
					.getRealPath(SystemComponent.getProperty("upload.tempPath"));*/
			User user = getCurrentUser(request);
			String tempBasePath = SystemComponent.getProperty("upload.tempPath");
			String pathDir = File.separator + "temp" + File.separator+ym_format.format(now)+File.separator + user.getUserId();
			File dirFile = new File(tempBasePath+pathDir);
			if (!dirFile.isDirectory()) {
				dirFile.mkdirs();
			}
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator iterator = multiRequest.getFileNames();
				while (iterator.hasNext()) {
					String key = iterator.next().toString();
					MultipartFile file = multiRequest.getFile(key);
					if (file != null) {
						// String filename=new
						// String(file.getOriginalFilename().getBytes("ISO8859-1"),"UTF-8");
						String name = file.getOriginalFilename();
						if (name.indexOf(".") == -1 && "blob".equals(name)) {
							name = name + ".png";
						}
						fileName = pathDir +File.separator + fileName
								+ name.substring(name.lastIndexOf("."))
										.toLowerCase();
						filePath = tempBasePath+ fileName;
						File fi = new File(filePath);
						fi.setWritable(true, false);
						file.transferTo(fi);
						map.put("code", HttpCode.HTTP_CODE_200);
					} else {
						map.put("code", HttpCode.HTTP_CODE_400);
						fileName = "请选择要上传的文件！";
					}
				}
			} else {
				map.put("code", HttpCode.HTTP_CODE_400);
				fileName = "请选择要上传的文件！";
			}
			map.put("imgName",  fileName);
		} catch (Exception ex) {
			map.put("code", HttpCode.HTTP_CODE_500);
			map.put("msg", "上传图片失败！");
			log.error("上传文件失败", ex);
		}
		return map;
	}
	
	 @RequestMapping("/upload2")
	 @ResponseBody
	 public Map<String,Object> upload2(HttpServletRequest request,HttpServletResponse response){
		 String fileName=UUID.randomUUID().toString();
		 Map<String, Object> map = new HashMap<String,Object>();
		 try{
			 response.setContentType("text/html;charset=utf-8");
			 //String filePath="";
			 String fileStr = request.getParameter("filename");
			 if(fileStr!=null &&!"".equals(fileStr)){
				 int index = fileStr.indexOf("base64");
				 if(index>0){
					 String preStr = fileStr.substring(0,index+7);
					 String prefix = preStr.substring(preStr.indexOf("/")+1,preStr.indexOf(";")).toLowerCase();
					 fileStr = fileStr.substring(fileStr.indexOf(",")+1);
			         String pathDir = request.getSession().getServletContext().getRealPath("/WEB-INF/resources/upload");
			         BASE64Decoder decoder = new BASE64Decoder();
			         byte[] bb = decoder.decodeBuffer(fileStr);
			         for (int i = 0; i < bb.length; ++i) {  
						if (bb[i] < 0) {// 调整异常数据  
							bb[i] += 256;  
						}  
					 } 
			         File dir = new File(pathDir);
			         if (!dir.exists()) {
			          dir.mkdirs();
			        }
			         String distPath = pathDir+File.separator+fileName+"."+prefix;
			         OutputStream out = new FileOutputStream(distPath);
			         out.write(bb);
			         out.flush();
			         out.close();
			         map.put("imgName", fileName+"."+prefix);
			         map.put("code", HttpCode.HTTP_CODE_200);
				 }else{
					 map.put("code", HttpCode.HTTP_CODE_400);
				 }
			 }else{
				 map.put("code", HttpCode.HTTP_CODE_400);
			 }
		 }catch (Exception e) {
			 map.put("code", HttpCode.HTTP_CODE_500);
			 map.put("msg", "上传失败！");
			 log.error("上传失败", e);
		}
		 return map;
	 }
	 
	
}
